//
//  CustomSwitch.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/11/17.
//

#import "CustomSwitch.h"

@interface CustomSwitch ()
@property (nonatomic,strong)UILabel *label;
@end

@implementation CustomSwitch
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
       
        self.layer.cornerRadius = 10;
        self.clipsToBounds = YES;
        self.backgroundColor = rgba(0, 145, 255, 1);
        [self addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
        
        self.label = [[UILabel alloc] init];
        self.label.text = @"弹 ";
        self.label.textColor = [UIColor grayColor];
        self.label.font = [UIFont systemFontOfSize:10];
        self.label.textAlignment = NSTextAlignmentCenter;
        self.label.backgroundColor = [UIColor whiteColor];
        self.label.layer.cornerRadius = 8;
        self.label.clipsToBounds = YES;
        [self addSubview:self.label];
        [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self);
            make.right.mas_equalTo(self).offset(-2);
            make.left.mas_equalTo(self).offset(17);
            make.width.height.offset(16);
        }];
    }
    return self;
}
- (void)switchAction:(UIButton *)sender
{
    sender.selected =!sender.selected;
    [UIView animateWithDuration:0.3 animations:^{
        [self.label mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self);
            if(sender.selected){
                make.left.mas_equalTo(self).offset(2);
                make.right.mas_equalTo(self).offset(-17);
                self.backgroundColor = [UIColor grayColor];
            }else{
                make.right.mas_equalTo(self).offset(-2);
                make.left.mas_equalTo(self).offset(17);
                self.backgroundColor = rgba(0, 145, 255, 1);
            }
            make.width.height.offset(16);
        }];
        [self layoutIfNeeded];
    }];
    
    if([self.delegate respondsToSelector:@selector(switchWithSelected:)]){
        [self.delegate switchWithSelected:sender.selected];
    }
}

@end
